package com.beone.admin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.base.SuperServiceImpl;
import com.base.common.util.BaseStringUtils;
import com.beone.admin.entity.BasePermission;
import com.beone.admin.entity.BaseRoleUser;
import com.beone.admin.entity.BaseUser;
import com.beone.admin.mapper.BaseUserMapper;
import com.beone.admin.service.BasePermissionService;
import com.beone.admin.service.BaseRoleUserService;
import com.beone.admin.service.BaseUserService;
import com.beone.admin.utils.PaginationGatagridTable;
import com.beone.admin.utils.ServiceUtils;
import com.base.common.util.algorithm.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * @Title 运维数据_系统用户信息表 服务实现类
 * @Author 覃球球
 * @Version 1.0 on 2018-01-25
 * @Copyright 长笛龙吟
 */
@Service("BaseUserService")
@Transactional
public class BaseUserServiceImpl extends SuperServiceImpl<BaseUserMapper, BaseUser> implements BaseUserService {

    @Autowired
    private BasePermissionService permissionsService;

    @Autowired
    private BaseRoleUserService roleUserService;

    private Logger logger = LoggerFactory.getLogger(BaseUserServiceImpl.class);

    /**
     * 根据用户名获取后台管理用户信息
     * @param name
     * @return
     */
    public BaseUser loadUserByUsername(String name){
        return baseMapper.loadUserByUsername(name);
    }

    /**
     * 是否supervisor用户
     * @param userId
     * @return  true 是   false 否
     */
    public boolean isSupervisor(Integer userId){
        if(1 == userId) { //supervisor user
            return true;
        }
        return false;
    }

    /**
     * 根据用户ID，获取用户所有的URL权限列表
     * @param userId 用户Id
     * @param actionType  page  表示只显示页面权限   all  显示所有权限
     * @return
     */
    public List<BasePermission> queryPermissions(String actionType,Integer userId) {
        if(isSupervisor(userId)){ //supervisor user 获取所有权限信息
            return permissionsService.getAllPermissionses(actionType);
        }
        //根据用户Id 获取权限信息
        return permissionsService.getPermissionsesByUserId(actionType, userId);
    }

    /**
     * 根据用户Id, 修改用户密码
     * @return
     */
    public JSONObject updatePwd(String oldPwd,String newPassword, Integer userId) {
        JSONObject jsonObject = new JSONObject();
        BaseUser user = baseMapper.selectById(userId);
        String oldPassword = DigestUtils.md5(oldPwd);
        if (!oldPassword.equals(user.getUserPwd())) {
            jsonObject.put("code", "fail");
            jsonObject.put("msg", "原始密码错误！");
            return jsonObject;
        }

        newPassword = DigestUtils.md5(newPassword);
        BaseUser newUser = new BaseUser();
        newUser.setUserId(userId);
        newUser.setUserPwd(newPassword);
        int result = baseMapper.updateById(newUser);
        if (result == 1) {
            jsonObject.put("code", "success");
            jsonObject.put("msg", "密码修改成功，请重新登录！");
        } else {
            jsonObject.put("code", "fail");
            jsonObject.put("msg", "密码修改失败！");
        }
        return jsonObject;
    }

    /**
     * 分页显示后台用户列表
     * @param user
     * @param currPage  当前页码
     * @param pageSize  每页显示记录数
     * @return
     */
    public PaginationGatagridTable getUserPagination(BaseUser user, int currPage, int pageSize){
        EntityWrapper<BaseUser> entityWrapper = new EntityWrapper<BaseUser>();
        entityWrapper.gt("u.user_id", 1); //过滤 Supervisor用户

        if(StringUtils.isNotBlank(user.getUserAccount())){
            entityWrapper.like("u.user_account", BaseStringUtils.filterSpecSpecialValue(user.getUserAccount()));
        }

        if(StringUtils.isNotBlank(user.getUserName())){
            entityWrapper.like("u.user_name",  BaseStringUtils.filterSpecSpecialValue(user.getUserName()));
        }

        if(StringUtils.isNotBlank(user.getUserMobile())){
            entityWrapper.like("u.user_mobile", BaseStringUtils.filterSpecSpecialValue(user.getUserMobile()));
        }

        Page page = new Page<BaseUser>(currPage,pageSize);
        List<BaseUser> rows = baseMapper.selectUserPage(page, entityWrapper);
        return ServiceUtils.createGatagridTableJson(page,rows);
    }

    /**
     * 保存用户信息
     */
    @Transactional
    public boolean saveUser(BaseUser user){
        Integer result = 0;
        if(user.getUserId() == null || user.getUserId() <= 0){ //userId空 或 小于等于0 为新增操作
            user.setCreateTime((int)(System.currentTimeMillis()/1000));
//            user.setUserStatus("01"); //正常状态
            user.setIsAdmin(0); //非super用户
            result = baseMapper.insert(user);
        }else {
            result = baseMapper.updateById(user); //更新操作

            //删除用户角色关系
            roleUserService.deleteRoleUserRelationByUserId(user.getUserId());
        }

        //保存用户角色关系表
        String[] roleIds = user.getRoleIds().split(",");
        for (int i = 0; i < roleIds.length; i++){
            BaseRoleUser roleUser = new BaseRoleUser();
            roleUser.setRoleId(Integer.valueOf(roleIds[i]));
            roleUser.setUserId(user.getUserId());
            roleUserService.insert(roleUser);
        }

        if(result > 0){
            return true;
        }
        return false;
    }

    /**
     * 检查用户是否存在
     * @param userId
     * @param userAccount
     * @return  true  不存在   false 存在
     */
    public boolean checkUserNotExist(Integer userId, String userAccount){
        EntityWrapper<BaseUser> entityWrapper = new EntityWrapper<BaseUser>();
        entityWrapper.eq("user_account", userAccount);
        if(userId != null && userId > 0){
            entityWrapper.ne("user_id", userId);
        }

        Integer count = baseMapper.selectCount(entityWrapper);

        if(count > 0 ){  //账户已存在
            return false;
        }
        return true;
    }
}
